const express = require('express');
const puppeteer = require('puppeteer-cn');
const bodyParser = require('body-parser');
const crypto = require('crypto');
const path = require('path');
const fs = require('fs-extra');
const rootPath = path.join(__dirname, '/public');

function getMd5Path(query) {
    const hash = crypto.createHash('md5');
    return hash.update(query, 'utf-8').digest('hex')+'.png';
}

const app = express();
app.use(express.static(rootPath));
app.use(bodyParser.urlencoded({ extended: false }));
app.use(bodyParser.json());
app.use(bodyParser.text());

app.get('*', async (req, res, next)=>{
    const search = req._parsedUrl.search;
    if (/wmts/.test(req.path)) {
        const image = path.join(rootPath, req.path, getMd5Path(search));
        if (fs.existsSync(image)) {
            console.log("[found]:", req.path);
            return fs.createReadStream(image).pipe(res);
        } else {
            console.log("======= not found", req.url);
        }
    } else {
        next();
    }
});

app.listen(4000, function() {
    console.log('server listen on: http://localhost:4000');
});
